# koroFileHeader at Yungoal acer
# Create: 2022-10-26 10:53:37
# LastEdit: 2022-10-26 15:45:07
"""Daily 系列视图"""
__author__ = '749B'

import json
import random

from django.db.models import Sum
from django.shortcuts import render
from django.utils import dateparse

from pyecharts.charts import Bar
from pyecharts import options as opts

from .. import models
from .restapi import JsonResponse

import logging
logger = logging.getLogger(__name__)
logger.success = lambda msg, *args, **kwargs: logger.log(25, msg, *args, **kwargs)  # type: ignore


# Create your views here.
def daily_picker(request):
    sub_list = models.Subscriptions.objects.values('id', 'name') 
    return render(
        request, 
        "billing/daily_picker.html", 
        {'sub_list': sub_list},
        )

def cost_daily_picker(request):
    subid = request.GET.get('subid')
    qs = models.Detail.objects.all()
    if subid:
        qs = qs.filter(subscription_id=subid)

    qs_sub = qs  # 保留按订阅筛选的结果，如果日期筛选后没有记录，则使用这个结果
    start_date = dateparse.parse_date(request.GET.get('start_date') or '')
    end_date = dateparse.parse_date(request.GET.get('end_date') or '')
    error_msg = []
    if start_date and end_date and start_date > end_date:
        start_date, end_date = end_date, start_date
        error_msg.append('起止日期填反了')
    if start_date:
        qs = qs.filter(date__gte=start_date)
    if end_date:
        qs = qs.filter(date__lte=end_date)
    if not qs.exists():
        # 如果日期筛选后没有记录，就放弃日期筛选。要用数据库的方法判断是否有记录
        # 如果用Python的方法，首先会把目前的记录全部查询出来
        qs = qs_sub
        start_date, end_date = None, None
        error_msg.append('日期筛选后无记录返回最近30天')

    if start_date and end_date:
        # 按起止时间提供
        qs = qs.values('date').annotate(cost=Sum('extended_cost')).order_by('date')
    elif start_date:
        # 按起始时间，提供之后30天
        qs = qs.values('date').annotate(cost=Sum('extended_cost')).order_by('date')[:30]
    else:
        # 按结束时间，提供之前30天。如果起止时间都未提供，就是最近30天
        qs = qs.values('date').annotate(cost=Sum('extended_cost')).order_by('-date')[:30:-1]
    cost_sum = sum([q['cost'] for q in qs])
    start = min([q['date'] for q in qs])
    end = max([q['date'] for q in qs])
    datazoom_enable = (end - start).days > 30

    bar = Bar()
    bar.add_xaxis([ i['date'].strftime('%m-%d')  for i in qs ])
    bar.add_yaxis(f'每日消费', [ round(i['cost'], 2) for i in qs], color=random.choice(bar.colors))
    bar.set_global_opts(
        title_opts=opts.TitleOpts(
            title=f'消费金额: {cost_sum:.2f}', 
            subtitle=f'{start} - {end}    ERROR: {", ".join(error_msg)}' if error_msg else f'{start} - {end}',
            subtitle_textstyle_opts=opts.TextStyleOpts(color='red') if error_msg else None,
            ),
        legend_opts=opts.LegendOpts(selected_mode=False),
        datazoom_opts=opts.DataZoomOpts() if datazoom_enable else None,  # 下面有个选择x轴跨度的条
        )
    bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),  # 柱状图上显示数字
        )
    c = bar.dump_options_with_quotes()
    return JsonResponse(json.loads(c))


def last30days(request):
    """最近30天"""
    sub_list = models.Subscriptions.objects.values('id', 'name') 
    return render(
        request, 
        "billing/last30days.html", 
        {'sub_list': sub_list},
        )

def cost_last30days(request, span=30):
    subid = request.GET.get('subid')
    if subid:
        qs_sub = models.Detail.objects.filter(subscription_id=subid)
    else:
        qs_sub = models.Detail.objects.all()

    qs = qs_sub.values('date').annotate(cost=Sum('extended_cost')).order_by('-date')[:span:-1]
    cost_sum = sum([q['cost'] for q in qs])
    start = min([q['date'] for q in qs])
    end = max([q['date'] for q in qs])
    datazoom_enable = (end - start).days > 30
    curr_date = models.Detail.objects.latest('date').date

    bar = Bar()
    bar.add_xaxis([ i['date'].strftime('%m-%d')  for i in qs ])
    bar.add_yaxis(f'每日消费', [ round(i['cost'], 2) for i in qs], color=random.choice(bar.colors))
    bar.set_global_opts(
        title_opts=opts.TitleOpts(
            title=f'消费金额: {cost_sum:.2f}', 
            subtitle=f'{start} - {end}' + (' *' if curr_date != end else '')),
        legend_opts=opts.LegendOpts(selected_mode=False),
        datazoom_opts=opts.DataZoomOpts() if datazoom_enable else None,  # 下面有个选择x轴跨度的条
        )
    bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),  # 柱状图上显示数字
        )
    c = bar.dump_options_with_quotes()
    return JsonResponse(json.loads(c))
